package com.example.bookstore;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.concurrent.atomic.AtomicReference;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author 16582
 */
public class Login extends AppCompatActivity {


    private ImageView login;
    private ImageView register;
    private EditText account;
    private EditText password;
    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        login = (ImageView) findViewById(R.id.login);
        register = (ImageView) findViewById(R.id.register);
        account = (EditText) findViewById(R.id.account);
        password = (EditText) findViewById(R.id.password);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar!=null){
            actionBar.hide();
        }
        login.setOnClickListener(v -> {
            if ("".equals(account.getText().toString())) {
                Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
            } else if ("".equals(password.getText().toString())) {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            } else {
                String Account;
                String Password;
                Account = account.getText().toString();
                Password = password.getText().toString();
                user = new User();
                user.setAccount(Account);
                user.setPassword(Password);
                login(Account, Password);
            }
        });
        register.setOnClickListener(v -> {
            View view = LayoutInflater.from(this).inflate(R.layout.register, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(view).setTitle("注册用户").setIcon(R.drawable.rg);
            builder.setPositiveButton("注册", (dialog, which) -> {
                EditText a = (EditText) view.findViewById(R.id.account);//账号
                EditText p = (EditText) view.findViewById(R.id.password);//密码
                EditText rp = (EditText) view.findViewById(R.id.repeat_password);//重复密码
                if ("".equals(a.getText().toString())) {
                    Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
                } else if ("".equals(p.getText().toString())) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                } else if ("".equals(rp.getText().toString())) {
                    Toast.makeText(this, "请重复密码", Toast.LENGTH_SHORT).show();
                } else {
                    register(a.getText().toString(), p.getText().toString());
                }
            });
            builder.setNegativeButton("取消", (dialog, which) -> {
            });
            builder.show();
        });
    }

    private void login(String account, String password) {
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("account", account)
                        .add("password", password)
                        .build();
                Request request = new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/login")
                        .post(requestBody)
                        .build();
                Response response = client.newCall(request).execute();
                String result = response.body().string();
                String str;
                if ("1".equals(result)) {
                    str = "登录成功";
                } else if ("0".equals(result)) {
                    str = "密码错误";
                } else if ("-1".equals(result)) {
                    str = "账号错误";
                } else {
                    str = "服务器错误";
                }
                make(str);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
    }

    private void make(final String str) {
        runOnUiThread(() ->
                Toast.makeText(this, str, Toast.LENGTH_SHORT).show());
        if (str.equals("登录成功")){//登陆成功则跳转到MainActivity
            Intent intent = new Intent(Login.this, MainActivity.class);
            intent.putExtra("userAccount",user.getAccount());
            startActivity(intent);
            finish();
        }
    }

    private void register(String account, String password) {
        new Thread(() -> {
            try {
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new FormBody.Builder()
                        .add("account", account)
                        .add("password", password)
                        .build();
                Request request = new Request.Builder()
                        .url("http://www.fenchingking.top/BookStore/register")
                        .post(requestBody)
                        .build();
                Response response = client.newCall(request).execute();
                String str;
                String result = response.body().string();
                if ("1".equals(result)) {
                    str = "注册成功";
                } else if ("0".equals(result)) {
                    str = "此账号已存在";
                } else if ("-1".equals(result)) {
                    str = "注册失败";
                } else {
                    str = "服务器错误";
                }
                make(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}